package games;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.util.Random;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;

public class Impulse extends Game {
	/**
	 * 
	 */
	private static final long serialVersionUID=1L;

	public static final String NAME="ImpulseGame";
	private static final String ENDED="game_stopped";
	private static final String TIME_OUT="time_out";
	public static final String WINNER="winner";
	
	CoinPainter painter;

	JLabel timerLabel;
	JLabel moneyLabel;
	int totalTime=50;
	double totalMoney=5.00;
	int time=totalTime;
	double money;
	
	public Impulse(Runner runner) {
		super(runner,NAME);
	}
	
	public void init() {
		// Turn off metal's use of bold fonts
		UIManager.put("swing.boldMetal",Boolean.FALSE);
	}

	public void start() {
		initComponents();
	}

	public void run() {
		JFrame f=new JFrame("Impulse Game");
		f.setLayout(new BorderLayout());
		f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		this.init();
		this.start();
		f.add("Center",this);
		f.pack();
		f.setVisible(true);
		f.setSize(600,500);
	}
	
	public static void main(String[] args) {

		Impulse ap=new Impulse(new Runner("test","test"));
		ap.run();
	}
	
  protected int secondUpdate(Impulse game) {
  	int elapsedTime=clock.getElapsedTime()/1000;
  	
  	time=totalTime-elapsedTime;
  	money=totalMoney-elapsedTime/(float)10;
  	
  	if(time%5==0) {
  		painter.flip(this);
  	}
  	
    game.timerLabel.setText(String.format(" %d ", time));
    game.timerLabel.repaint();
    game.moneyLabel.setText(String.format(" $%.2f ", money));
    game.moneyLabel.repaint();
    //repaint();
    //System.err.println(game.timerLabel.getText());
    return 1000;
  }
  
	public void initComponents() {
		setLayout(new BorderLayout());
		Font font=new Font(Font.SERIF,Font.BOLD,50);
		
		timerLabel=new JLabel(Integer.toString(totalTime));//-clock.getElapsedTime()));
		moneyLabel=new JLabel(Double.toString(totalMoney));//-clock.getElapsedTime()));
		timerLabel.setFont(font);
		moneyLabel.setFont(font);

		main=new JPanel(new BorderLayout());
		header=new JPanel(new BorderLayout());
		
		header.add(BorderLayout.WEST,timerLabel);
		header.add(BorderLayout.EAST,moneyLabel);
		
		main.add(BorderLayout.NORTH,header);
		add(BorderLayout.NORTH,main);
		
		stop=new Painter("stop","Click to Stop");
		footer=new JPanel(new BorderLayout());
		footer.add(BorderLayout.EAST,stop);
		
		add(BorderLayout.SOUTH,footer);
		
		painter=new CoinPainter();
		painter.heads=loadImage("heads2");
		painter.tails=loadImage("tails");
		main.add(BorderLayout.CENTER,painter);
		
		
		//hmmm(NAME);
		clock=new Timing();
    addMouseListener(new MouseAdapter(){
      public void mousePressed(MouseEvent e){
        //get the mouse position
        //int xPos=e.getX();
        //int yPos=e.getY();
        log(ENDED,money);
        finished(NAME,time);
      }
    });
		
    Thread monitorThread = new Thread(new Runnable() {
      public synchronized void run() {
        // String expName= System.getProperty("GAME"); // look for automatic
        // run
        // if (expName!=null) {
        // Thread.yield(); loadGame(); opr8.setEnabled(false); proceed(); }
        while (!gameCompleted) {
        	clock.suspend();
          // System.err.println("monitorThread: "+clock.getElapsedTime());
        	//System.err.println(clock.getElapsedTime());//
          int delay = secondUpdate(Impulse.this); // pass this; avoid race
          clock.proceed();                                       // condition
          try {
            wait(delay);
          } catch (InterruptedException ie) {
            //System.err.println("monitorThread interrupted; WHY?");
          }
          
        }
        //secondUpdate(Impulse.this); // final update of clock
        // if (expName!=null) { suspend(); System.err.println("automatic
        // endG"); endGame(); }
        System.err.println("monitorThread.stopping " + clock.getElapsedTime());
        if(!gameCompleted) {
        	log(TIME_OUT,money);
        	finished(NAME,time);
        }
      }
    });
    monitorThread.start();
    proceed();
    //clock.waitUntil("Time expired",50000);
    //System.err.println("monitorThread.start()ed");
	}
	
}
class CoinPainter extends Component {
  /**
	 * 
	 */
	private static final long serialVersionUID=1L;

	int time = 300;
  
  boolean[] coins = {false,false,false,false,false};
  BufferedImage heads = null;
  BufferedImage tails = null;
  
  void flip(Impulse ip) {
  	Random r=new Random();
  	boolean winner=true;
    for(int i=0;i<coins.length;i++) {
    	coins[i]=r.nextBoolean();
    	if(!coins[i]) winner=false;
    }
    repaint();
    if(winner) {
    	ip.log(Impulse.WINNER,ip.totalMoney);
    	ip.finished(Impulse.NAME,time);
    }
  }
  public Dimension getPreferredSize(){
    return new Dimension(600, 200);
	}
  public void paint(Graphics g) {
    for(int i=0;i<coins.length;i++) {
    	drawImage(g,coins[i],i);
    }
	}
  public void drawImage(Graphics g,boolean side,int num) {
  	g.drawImage(side?heads:tails,num*100,50,null);
  }
}